package top.wshape1.rpc.message.serializer;

import lombok.extern.slf4j.Slf4j;
import top.wshape1.rpc.common.extension.ExtensionLoader;
import top.wshape1.rpc.config.JJRpcConfig;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2024-02-02
 */

@Slf4j
public class SerializerFactory {

    private static final ExtensionLoader<Serializer> loader = ExtensionLoader.getExtensionLoader(Serializer.class);

    private static Serializer defaultSerializer;

    /**
     * 获取指定序列化器
     *
     * @param type 序列化器的键
     * @return Serializer
     */
    public static Serializer getSerializer(String type) {
        return loader.getExtension(type);
    }

    /**
     * 获取默认的序列化器
     *
     * @return Serializer
     */
    public static Serializer getSerializer() {
        if (defaultSerializer == null)
            defaultSerializer = getSerializer(JJRpcConfig.CONFIG.getSerializer().getType());
        return defaultSerializer;
    }

    /**
     * 使用自定义序列化器来设置默认的消息序列化器
     *
     * @param serializer 自定义序列化器
     */
    public static void setSerializer(Serializer serializer) {
        if (serializer == null) {
            log.error("The custom serializer cannot be null. Use the default serializer.");
            return;
        }
        defaultSerializer = serializer;
    }


    public static void resetFactory() {
        loader.clearExtensionInstances();
        defaultSerializer = null;
    }


}
